package com.sgb.kjwl.view.ui.activity.enterprise;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;

import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;

import com.alibaba.fastjson.JSONObject;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bumptech.glide.Glide;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;

import com.sgb.kjwl.api.GsonManager;
import com.swgk.core.util.AttachmentStore;
import com.swgk.core.util.FileUtil;
import com.swgk.core.util.LogUtil;
import com.sgb.alimaplibrary.util.ToastUtil;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.BR;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityAddnewneedServiceBinding;
import com.sgb.kjwl.model.entity.NeedDetailsEntity;
import com.sgb.kjwl.model.entity.ParentAreaMeasureEntity;
import com.sgb.kjwl.model.entity.enterprise.IpPickSelectEntity;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.utils.FileUtils;
import com.sgb.kjwl.utils.KeyboardUtils;
import com.swgk.core.util.UiUtil;
import com.swgk.core.view.CityPickBuilder;
import com.swgk.core.view.CityPickView;
import com.sgb.kjwl.viewmodel.enterprise.AddNeed_ServiceModel;
import com.swgk.core.customview.InputFilterUtils;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.ClickUtils;
import com.swgk.core.util.MToast;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 发布找服务
 */
public class AddNeed_ServiceActivity extends AppActivity {


    private ActivityAddnewneedServiceBinding mBinding;
    private AddNeed_ServiceModel mModel;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;
    private Thread thread;
    private static final int MSG_LOAD_DATA2 = 0x0001;
    private static final int MSG_LOAD_SUCCESS2 = 0x0002;
    private static final int MSG_LOAD_FAILED2 = 0x0003;
    private Thread thread2;
    private boolean isLoaded = false;
    private boolean isLoaded2 = false;
    // 一级联动数据
    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> addressEntityList = new ArrayList<>();
    // 二级联动数据
    private List<List<AddressEntity<List<AddressEntity>>>> opt2 = new ArrayList<>();
    // 三级联动数据
    private List<List<List<AddressEntity>>> opt3 = new ArrayList<>();
    private int cityPosition1;
    private int cityPosition2;
    private int cityPosition3;
    private String mProvinceNo;//省No
    private String mCityNo;//市No
    private String mAreaNameNo;//区No
    String province;//省
    String city;//市
    String areaName;//区
    // 文件路径
    private String filePath;
    String fileName;
    String fileSize;
    String fileType;

    OptionsPickerView<IpPickSelectEntity> mBillTypeOptionsPickerView;//发票类型

    // 打开任务管理器
    public static final int REQUESTCODE_OPEN_FILECHOOSER = 102;

    @Override
    protected void initView() {
        super.initView();
        mModel = new AddNeed_ServiceModel();
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_addnewneed_service);
        mBinding.setVariable(BR.mServicermodel,mModel);
        mBinding.setLifecycleOwner(this);

        mBinding.llChooseNeedFapiao.setOnClickListener(this);
        mBinding.llChooseNeedLocation.setOnClickListener(this);
        mBinding.tvUploadAnnex.setOnClickListener(this);
        mBinding.tvAnnexDelete.setOnClickListener(this);
        mBinding.ivDeleteLocation.setOnClickListener(this);
        mBinding.ivDeleteFapiao.setOnClickListener(this);
        InputFilterUtils.setEditTextInhibitInputSpaChat(mBinding.tvName, 15);
        InputFilterUtils.setEditTextInhibitInputSpaChat(mBinding.tvinputtitle, 50);

        mBinding.ediMoney.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence editable, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String s = editable.toString();
                mBinding.ediMoney.removeTextChangedListener(this);

                if (s.contains(".")) {
                    mBinding.ediMoney.setFilters(new InputFilter[]{new InputFilter.LengthFilter(10 + 3 + 1)});
                    if (s.length() - 1 - s.indexOf(".") > 2) {
                        s = s.substring(0,
                                s.indexOf(".") + 2 + 1);
                        editable.replace(0, editable.length(), s.trim());
                    }
                } else {
                    mBinding.ediMoney.setFilters(new InputFilter[]{new InputFilter.LengthFilter(10 + 1)});
                    if (s.length() > 10) {
                        s = s.substring(0, 10);
                        editable.replace(0, editable.length(), s.trim());
                    }
                }
                if (s.trim().equals(".")) {
                    s = "0" + s;
                    editable.replace(0, editable.length(), s.trim());
                }

                if (s.startsWith("0") && s.trim().length() > 1) {
                    if (!s.substring(1, 2).equals(".")) {
                        editable.replace(0, editable.length(), "0");
                    }
                }
                mBinding.ediMoney.addTextChangedListener(this);
            }
        });

        mModel.name.observe(this,String ->{
            if(String.indexOf(" ")>-1) {
                mModel.name.postValue(String.trim());
            }
        });
        mModel.contacts_name.observe(this,String ->{
            if(String.indexOf(" ")>-1) {
                mModel.contacts_name.postValue(String.trim());
            }
        });

        if(getIntent().getSerializableExtra("data")!=null){
            mModel.data=(NeedDetailsEntity)getIntent().getSerializableExtra("data");
            mModel.setdata();
            String path = "";
            if(!TextUtils.isEmpty(mModel.data.getProvinceName())){
                path = mModel.data.getProvinceName();
                mModel.provinceName = mModel.data.getProvinceName();
            }
            if(!TextUtils.isEmpty(mModel.data.getCityName())){
                path=path+mModel.data.getCityName();
                mModel.cityName = mModel.data.getCityName();
            }
            if(!TextUtils.isEmpty(mModel.data.getAreaName())){
                path=path+mModel.data.getAreaName();
                mModel.areaName = mModel.data.getAreaName();
            }

            if(!TextUtils.isEmpty(mModel.data.getProvinceCode())){
                mModel.provinceCode = mModel.data.getProvinceCode();
            }
            if(!TextUtils.isEmpty(mModel.data.getCityCode())){
                mModel.cityCode = mModel.data.getCityCode();
            }
            if(!TextUtils.isEmpty(mModel.data.getAreaCode())){
                mModel.areaCode = mModel.data.getAreaCode();
            }
            if(!TextUtils.isEmpty(path)) {
                mBinding.tvChooseLocation.setText(path);
                mBinding.ivDeleteLocation.setVisibility(View.VISIBLE);
            }
            if(!TextUtils.isEmpty(mModel.data.getDemandAttachment())) {
                mModel.demandAttachment = mModel.data.getDemandAttachment();
                JSONObject jsonObject = JSONObject.parseObject(mModel.data.getDemandAttachment());
                if (jsonObject.get("name") != null) {
                    fileName = jsonObject.getString("name");
                }
                if (jsonObject.get("size") != null) {
                    fileSize = jsonObject.getString("size");
                }
                if (jsonObject.get("type") != null) {
                    fileType = jsonObject.getString("type");
                }
                mBinding.tvUploadAnnex.setVisibility(View.GONE);
                mBinding.rlAnnexInfo.setVisibility(View.VISIBLE);
                mBinding.tvAnnexName.setText(fileName);
                mBinding.tvAnnexSize.setText(fileSize);
                switch (fileType) {
                    case "application/zip":
                    case "application/rar":
                        Glide.with(this).load(R.mipmap.icon_zip).into(mBinding.ivAnnexSimple);
                        break;
                    case "image/png":
                    case "image/jpeg":
                        Glide.with(this).load(R.mipmap.icon_image).into(mBinding.ivAnnexSimple);
                        break;
                    case "application/pdf":
                        Glide.with(this).load(R.mipmap.icon_pdf2).into(mBinding.ivAnnexSimple);
                        break;
                }
                mModel.InvoiceRequirements = mModel.data.getInvoiceRequirements()+"";
                mBinding.tvChooseFapiao.setText( null==mModel.data.getInvoiceRequirements()?"": mModel.data.getInvoiceRequirements()==0?"不需要发票":  mModel.data.getInvoiceRequirements()==1?"增值税普通发票":  mModel.data.getInvoiceRequirements()==2?"增值税专用发票":"");
                if(!TextUtils.isEmpty(mBinding.tvChooseFapiao.getText().toString())){
                    mBinding.ivDeleteFapiao.setVisibility(View.VISIBLE);
                }
            }
        }
        mModel.toast_message.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                ToastUtil.show(AddNeed_ServiceActivity.this,s);
            }
        });
        mModel.showloading_diag.observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(Integer integer) {
                switch (integer){
                    case 1:
                        DialogHelper.showProgressDialog(AddNeed_ServiceActivity.this, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
                        break;
                    case 2:
                        DialogHelper.dismissProgressDialog();
                        break;

                    case 3://提交成功
                        DialogHelper.dismissProgressDialog();
//                        if(mModel.data!=null){
//                            Intent mintent = new Intent();
//                            mintent.putExtra("data",(Serializable)mModel.data);
//                            setResult(AddNeedDetailActivity.REQUEST_CODE,mintent);
//                        }
                        AddNeedListActivity.startactivity(AddNeed_ServiceActivity.this);
                        finish();
                        break;
                }
            }
        });

        mModel.is_bargaining.observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                if(aBoolean){
                    mModel.money.postValue("");
                    mBinding.ediMoney.setEnabled(false);
                }else{
                    mBinding.ediMoney.setEnabled(true);
                }
            }
        });
        mModel.money.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                if(!TextUtils.isEmpty(s)){
                    mModel.is_bargaining.postValue(false);
                }
            }
        });

        mModel.ldServiceType.observe(this, new Observer<List<ParentAreaMeasureEntity<List<ParentAreaMeasureEntity<List<ParentAreaMeasureEntity>>>>>>() {
            @Override
            public void onChanged(List<ParentAreaMeasureEntity<List<ParentAreaMeasureEntity<List<ParentAreaMeasureEntity>>>>> parentAreaEntities) {
                if(parentAreaEntities.size()>0) {
                    showAddressPop(setData(parentAreaEntities));
                }
            }
        });
        mModel.ldServiceCity.observe(this, this::showAddressPop2);
        mModel.mBillTypeListLiveData.observe(this, this::showBillPopwindow);
        mModel.stringLiveData.observe(this, this::setDemandAttachment);

    }

    private void setDemandAttachment(String fileUrl) {
        if (!TextUtils.isEmpty(fileUrl)) {
            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("name", fileName);
            jsonObject.addProperty("url", fileUrl);
            jsonObject.addProperty("size", fileSize);
            jsonObject.addProperty("type", fileType);
            mModel.demandAttachment = jsonObject.toString();
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_choose_need_location://选择服务城市
                if (!ClickUtils.isDoubleClick()) {
                    if (addressEntityList != null && addressEntityList.size() > 0) {
                        showCityPop();
                    } else {
                        mModel.getAddressModel(this);
                    }
                }
                break;
            case R.id.ll_choose_need_fapiao://选择服务城市
                if (!ClickUtils.isDoubleClick()) {
                    if (mBillTypeOptionsPickerView != null) {
                        mBillTypeOptionsPickerView.show();
                    } else {
                        mModel.getPatentTypeOption();
                    }
                }
                break;
            case R.id.tv_upload_annex://上传文件
                Intent fileIntent = new Intent(Intent.ACTION_GET_CONTENT);
                fileIntent.addCategory(Intent.CATEGORY_OPENABLE);
                //设置类型
                fileIntent.setType("application/zip|image/png|application/pdf|application/rar|image/jpeg");
                //在API>=19之后设置多个类型采用以下方式，setType不再支持多个类型
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    fileIntent.putExtra(Intent.EXTRA_MIME_TYPES,
                            new String[]{"application/zip", "image/png", "application/pdf", "application/rar", "image/jpeg"});
                }
                startActivityForResult(fileIntent, REQUESTCODE_OPEN_FILECHOOSER);
                break;
            case R.id.tv_annex_delete://删除附件
                if (!ClickUtils.isDoubleClick()) {
                    mModel.demandAttachment = "";
                    fileName = "";
                    fileSize = "";
                    fileType = "";
                    mBinding.tvUploadAnnex.setVisibility(View.VISIBLE);
                    mBinding.rlAnnexInfo.setVisibility(View.GONE);
                }
                break;
            case R.id.iv_delete_location:
                mModel.provinceCode = "";
                mModel.provinceName = "";
                mModel.cityCode = "";
                mModel.cityName = "";
                mModel.areaCode = "";
                mModel.areaName = "";
                mBinding.tvChooseLocation.setText("");
                mBinding.ivDeleteLocation.setVisibility(View.GONE);
                break;
            case R.id.iv_delete_fapiao:
                mModel.InvoiceRequirements = "";
                mBinding.tvChooseFapiao.setText("");
                mBinding.ivDeleteFapiao.setVisibility(View.GONE);
                break;
        }
    }


    public void showAddressPop2(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> datas) {
        this.addressEntityList = datas;
        if (isLoaded2) {
            showCityPop();
        } else {
            mHandler2.sendEmptyMessage(MSG_LOAD_DATA2);
        }
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler2 = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA2:
                    if (thread2 == null) {//如果已创建就不再重新创建子线程了
                        thread2 = new Thread(() -> {
                            // 子线程中解析省市区数据
                            initJsonData2();
                        });
                        thread2.start();
                    }
                    break;
                case MSG_LOAD_SUCCESS2:
                    showCityPop();
                    isLoaded2 = true;
                    thread2 = null;
                    break;
                case MSG_LOAD_FAILED2:
                    break;
            }
        }
    };

    private void initJsonData2() {
        //城市列表
        List<AddressEntity<List<AddressEntity>>> cityList;
        //区域列表
        List<List<AddressEntity>> areaList;
        for (int x = 0; x < addressEntityList.size(); x++) {
            cityList = new ArrayList<>();
            areaList = new ArrayList<>();
            opt2.add(addressEntityList.get(x).getChildren());
            for (int i = 0; i < addressEntityList.get(x).getChildren().size(); i++) {
                cityList.add(addressEntityList.get(x).getChildren().get(i));
                List<AddressEntity> cityAreaList = new ArrayList<>();
                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (addressEntityList.get(x).getChildren().get(i).getChildren() == null
                        || addressEntityList.get(x).getChildren().get(i).getChildren().size() == 0) {
                    cityAreaList.add(null);
                } else {
                    cityAreaList.addAll(addressEntityList.get(x).getChildren().get(i).getChildren());
                }
                areaList.add(cityAreaList);
            }
            opt3.add(areaList);
        }
        mHandler2.sendEmptyMessage(MSG_LOAD_SUCCESS2);
    }


    /**
     * 选择服务城市 单选
     */
    private void showCityPop() {
        CityPickView cityOption = new CityPickBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                if (opt3.get(options1).get(options2).get(options3) == null) {
                    province = addressEntityList.get(options1).getName();
                    city = opt2.get(options1).get(options2).getName();
                    areaName = "";
                    mProvinceNo = addressEntityList.get(options1).getNo();
                    mCityNo = opt2.get(options1).get(options2).getNo();
                    mAreaNameNo = "";
                    cityPosition3 = options3;
                    cityPosition2 = options2;
                    cityPosition1 = options1;
                    StringBuilder builder = new StringBuilder();
                    builder.append(province);
                    if (!TextUtils.isEmpty(city)) {
                        builder.append("-").append(city);
                    }
                    if (!TextUtils.isEmpty(areaName)) {
                        builder.append("-").append(areaName);
                    }
                    mBinding.tvChooseLocation.setText(builder.toString());

                } else {
                    province = addressEntityList.get(options1).getName();
                    city = opt2.get(options1).get(options2).getName();
                    areaName = opt3.get(options1).get(options2).get(options3).getName();
                    mProvinceNo = addressEntityList.get(options1).getNo();
                    mCityNo = opt2.get(options1).get(options2).getNo();
                    mAreaNameNo = opt3.get(options1).get(options2).get(options3).getNo();
                    cityPosition3 = options3;
                    cityPosition2 = options2;
                    cityPosition1 = options1;
                    StringBuilder builder = new StringBuilder();
                    builder.append(province);
                    if (!TextUtils.isEmpty(city)) {
                        builder.append("-").append(city);
                    }
                    if (!TextUtils.isEmpty(areaName)) {
                        builder.append("-").append(areaName);
                    }
                    mBinding.tvChooseLocation.setText(builder.toString());
                }
                mModel.provinceCode = mProvinceNo;
                mModel.provinceName = province;
                mModel.cityCode = mCityNo;
                mModel.cityName = city;
                mModel.areaCode = mAreaNameNo;
                mModel.areaName = areaName;
                mBinding.ivDeleteLocation.setVisibility(View.VISIBLE);
            }
        }).setCancelText("取消").setSubCalSize(15)
                .setCancelColor(Color.parseColor("#666666"))
                .setTitleColor(Color.parseColor("#969696")).setTitleSize(15)
                .setSubmitText("确定")
                .setSubmitColor(Color.parseColor("#5792FD"))
                .setTextColorCenter(Color.parseColor("#ff333333"))
                .setContentTextSize(15)
                .setLineSpacingMultiplier(2.5f)
                .setDividerColor(Color.parseColor("#EDEDED"))
                .build();
        cityOption.setPicker(addressEntityList, opt2, opt3);
        cityOption.setSelectOptions(cityPosition1, cityPosition2, cityPosition3);
        cityOption.show();
    }

    private void showBillPopwindow(List<IpPickSelectEntity> ipPickSelectEntities) {
        if (mBillTypeOptionsPickerView == null) {
            mBillTypeOptionsPickerView = new OptionsPickerBuilder(this, (options1, options2, options3, v) -> {
                mBinding.tvChooseFapiao.setText(ipPickSelectEntities.get(options1).getName());
                mModel.InvoiceRequirements = ipPickSelectEntities.get(options1).getId();
                mBinding.ivDeleteFapiao.setVisibility(View.VISIBLE);
            }).setCancelText("取消").setSubCalSize(15)
                    .setCancelColor(Color.parseColor("#666666"))
                    .setTitleColor(Color.parseColor("#969696")).setTitleSize(15)
                    .setSubmitText("确定")
                    .setSubmitColor(Color.parseColor("#5792FD"))
                    .setTextColorCenter(Color.parseColor("#ff333333"))
                    .setContentTextSize(15)
                    .setLineSpacingMultiplier(2.5f)
                    .setDividerColor(Color.parseColor("#EDEDED"))
                    .build();
            mBillTypeOptionsPickerView.setPicker(ipPickSelectEntities);
            mBillTypeOptionsPickerView.setSelectOptions(0);
            mBillTypeOptionsPickerView.show();
        }
        KeyboardUtils.hideSoftInput(this);
    }

    public void showAddressPop(List<ParentAreaMeasureEntity<List<ParentAreaMeasureEntity<List<ParentAreaMeasureEntity>>>>> datas) {
        mModel.typeEntityList = datas;
        if (isLoaded) {
            showServiceTypePop("");
        } else {
            mHandler.sendEmptyMessage(MSG_LOAD_DATA);
        }
    }


    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了
                        thread = new Thread(() -> {
                            // 子线程中解析数据
                            initJsonData();
                        });
                        thread.start();
                    }
                    break;
                case MSG_LOAD_SUCCESS:
                    showServiceTypePop("");
                    isLoaded = true;
                    thread = null;
                    break;
                case MSG_LOAD_FAILED:
                    break;
            }
        }
    };

    private void initJsonData() {
        //城市列表
        List<ParentAreaMeasureEntity<List<ParentAreaMeasureEntity>>> cityList;
        //区域列表
        List<List<ParentAreaMeasureEntity>> areaList;
        ParentAreaMeasureEntity ParentAreaMeasureEntity = new ParentAreaMeasureEntity();
        ParentAreaMeasureEntity.setName("");
        ParentAreaMeasureEntity.setNo("");
        for (int x = 0; x < mModel.typeEntityList.size(); x++) {
            cityList = new ArrayList<>();
            areaList = new ArrayList<>();
            if (mModel.typeEntityList.get(x).getChildren() == null || mModel.typeEntityList.get(x).getChildren().size() == 0) {
                List<ParentAreaMeasureEntity<List<ParentAreaMeasureEntity>>> cityList1 = new ArrayList<>();
                cityList1.add(ParentAreaMeasureEntity);
                mModel.opt2.add(cityList1);
                List<ParentAreaMeasureEntity> cityAreaList = new ArrayList<>();
                cityAreaList.add(ParentAreaMeasureEntity);
                areaList.add(cityAreaList);

            } else {
                mModel.opt2.add(mModel.typeEntityList.get(x).getChildren());
                for (int i = 0; i < mModel.typeEntityList.get(x).getChildren().size(); i++) {
                    cityList.add(mModel.typeEntityList.get(x).getChildren().get(i));
                    List<ParentAreaMeasureEntity> cityAreaList = new ArrayList<>();
                    //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                    if (mModel.typeEntityList.get(x).getChildren().get(i).getChildren() == null
                            || mModel.typeEntityList.get(x).getChildren().get(i).getChildren().size() == 0) {
                        cityAreaList.add(ParentAreaMeasureEntity);
                    } else {
                        cityAreaList.addAll(mModel.typeEntityList.get(x).getChildren().get(i).getChildren());
                    }
                    areaList.add(cityAreaList);
                }
            }
            mModel.opt3.add(areaList);

        }
        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);
    }


    public List<ParentAreaMeasureEntity<List<ParentAreaMeasureEntity<List<ParentAreaMeasureEntity>>>>> setData(List<ParentAreaMeasureEntity<List<ParentAreaMeasureEntity<List<ParentAreaMeasureEntity>>>>> listDatas) {
        String cityListsStr = GsonManager.getInstance().getGson().toJson(listDatas);
        List<ParentAreaMeasureEntity<List<ParentAreaMeasureEntity<List<ParentAreaMeasureEntity>>>>> list = GsonManager.getInstance().getGson().fromJson(cityListsStr, new TypeToken<List<ParentAreaMeasureEntity<List<ParentAreaMeasureEntity<List<ParentAreaMeasureEntity>>>>>>() {
        }.getType());
        ParentAreaMeasureEntity ParentAreaMeasureEntity = new ParentAreaMeasureEntity();
        ParentAreaMeasureEntity.setName("");
        ParentAreaMeasureEntity.setNo("");
//        list.add(0, ParentAreaMeasureEntity);
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getChildren() == null || list.get(i).getChildren().size() == 0)
                continue;
//            list.get(i).getChildren().add(0, ParentAreaMeasureEntity);
            for (int j = 0; j < list.get(i).getChildren().size(); j++) {
                if (list.get(i).getChildren().get(j).getChildren() == null || list.get(i).getChildren().get(j).getChildren().size() == 0)
                    continue;
//                list.get(i).getChildren().get(j).getChildren().add(0, ParentAreaMeasureEntity);
            }
        }
        return list;
    }



    /**
     * 选择服务类型
     *
     * @param title 弹窗标题
     */
    private void showServiceTypePop(String title) {
        CityPickView cityOption = new CityPickBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                String areaName = "";
                if (mModel.opt3.get(options1).get(options2).get(options3) == null) {
                    areaName = "";
                } else {
                    areaName = mModel.opt3.get(options1).get(options2).get(options3).getName();
                   mModel.typePosition3 = options3;
                }
                StringBuilder builder = new StringBuilder();
                builder.append(mModel.typeEntityList.get(options1).getName());
                if (!TextUtils.isEmpty(mModel.opt2.get(options1).get(options2).getName())&&!mModel.opt2.get(options1).get(options2).getName().equals("不限")) {
                    builder.append("-").append(mModel.opt2.get(options1).get(options2).getName());
                }
                if (!TextUtils.isEmpty(areaName)&&!areaName.equals("不限")) {
                    builder.append("-").append(areaName);
                }
                mModel.typePosition1 = options1;
                mModel.typePosition2 = options2;
                mModel. mServiceFirstNo = mModel.typeEntityList.get(options1).getId();
                mModel.mServiceSecondNo = mModel.opt2.get(options1).get(options2).getId();
                mModel. mServiceThirdNo = mModel.opt3.get(options1).get(options2).get(options3).getId();
                mModel.mServiceFirstname = mModel.typeEntityList.get(options1).getName();
                mModel.mServiceSecondname = mModel.opt2.get(options1).get(options2).getName();
                mModel.mServiceThirdname = mModel.opt3.get(options1).get(options2).get(options3).getName();
                mModel.service_class.postValue(builder.toString());

            }
        }).setCancelText("取消").setSubCalSize(15)
                .setCancelColor(Color.parseColor("#666666"))
                .setTitleText(title)
                .setTitleColor(Color.parseColor("#969696")).setTitleSize(15)
                .setSubmitText("确定")
                .setSubmitColor(Color.parseColor("#5792FD"))
                .setTextColorCenter(Color.parseColor("#ff333333"))
                .setContentTextSize(15)
                .setLineSpacingMultiplier(2.5f)
                .setDividerColor(Color.parseColor("#EDEDED"))
                .build();
        cityOption.setPicker(mModel.typeEntityList, mModel.opt2, mModel.opt3);
        cityOption.setSelectOptions(mModel.typePosition1, mModel.typePosition2, mModel.typePosition3);
        cityOption.show();
    }




    public static void startactivity(Context mContext){

        Intent mIntent = new Intent();
        mIntent.setClass(mContext,AddNeed_ServiceActivity.class);
        mContext.startActivity(mIntent);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == REQUESTCODE_OPEN_FILECHOOSER) {//选择文件返回
                if (data == null) {
                    LogUtil.d("TAG", "onActivityResult chooseFile data is null");
                    return;
                }
                handleFileChoose(data);
            }
        }
    }

    private void handleFileChoose(Intent data) {
        Uri uri = data.getData();
//        binding.rlFilename.setVisibility(View.VISIBLE);
        /****
         * //使用第三方应用打开
         */
        if ("file".equalsIgnoreCase(uri.getScheme())) {
            filePath = uri.getPath();
            if (checkFileSize(filePath)) {
                mBinding.tvUploadAnnex.setVisibility(View.GONE);
                mBinding.rlAnnexInfo.setVisibility(View.VISIBLE);
                fileName = new File(filePath).getName();
                long fileLength = AttachmentStore.getFileLength(filePath);
                fileSize = UiUtil.bytes2kb(fileLength);
                fileType = FileUtil.getMimeType(new File(filePath));
                mBinding.tvAnnexName.setText(fileName);
                mBinding.tvAnnexSize.setText(fileSize);
                switch (fileType) {
                    case "application/zip":
                    case "application/rar":
                        Glide.with(this).load(R.mipmap.icon_zip).into(mBinding.ivAnnexSimple);
                        break;
                    case "image/png":
                    case "image/jpeg":
                        Glide.with(this).load(R.mipmap.icon_image).into(mBinding.ivAnnexSimple);
                        break;
                    case  "application/pdf":
                        Glide.with(this).load(R.mipmap.icon_pdf2).into(mBinding.ivAnnexSimple);
                        break;
                }
                mModel.uploadSingleImage(this, new File(filePath), 1, true);
            }
            LogUtil.d("TAG", "handleFileChoose uri.getScheme():" + filePath);
            return;
        }
        /***
         * //4.4以后
         */
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
            filePath = FileUtils.getPath(this, uri);
        } else {//4.4以下下系统调用方法
            filePath = FileUtils.getRealPathFromURI(uri, this);
        }
        if (checkFileSize(filePath)) {
            mBinding.tvUploadAnnex.setVisibility(View.GONE);
            mBinding.rlAnnexInfo.setVisibility(View.VISIBLE);
            fileName = new File(filePath).getName();
            long fileLength = AttachmentStore.getFileLength(filePath);
            fileSize = UiUtil.bytes2kb(fileLength);
            fileType = FileUtil.getMimeType(new File(filePath));
            mBinding.tvAnnexName.setText(fileName);
            mBinding.tvAnnexSize.setText(fileSize);
            switch (fileType) {
                case "application/zip":
                case "application/rar":
                    Glide.with(this).load(R.mipmap.icon_zip).into(mBinding.ivAnnexSimple);
                    break;
                case "image/png":
                case "image/jpeg":
                    Glide.with(this).load(R.mipmap.icon_image).into(mBinding.ivAnnexSimple);
                    break;
                case  "application/pdf":
                    Glide.with(this).load(R.mipmap.icon_pdf2).into(mBinding.ivAnnexSimple);
                    break;
            }
            mModel.uploadSingleImage(this, new File(filePath), 1, true);
        }
        LogUtil.d("TAG", "handleFileChoose filePath:" + filePath);
    }

    /**
     * 检查文件大小
     *
     * @param filePath 文件路径
     * @return 文件大小
     */
    private boolean checkFileSize(String filePath) {
        float sizeCount = 0f;
        long fileLength = AttachmentStore.getFileLength(filePath);
        String fileSize = FileUtil.formatFileSize(fileLength, FileUtil.SizeUnit.MB);
        if (fileSize.contains("MB")) {
            String fileSizeCount = fileSize.replace("MB", "");
            if (!TextUtils.isEmpty(fileSizeCount)) {
                sizeCount = Float.parseFloat(fileSizeCount);
                if (sizeCount > 20) {
                    MToast.showToast(this, "请上传20MB内的文件！");
                    return false;
                }
            }
        }
        return true;
    }

}
